import { useLocation, useNavigate } from 'react-router-dom';
import { useEffect, useRef } from 'react';
import { customHistory } from '../custom-browser-router/custom-browser-router';
import { whiteRoutes } from '../../../whiteRoutes';
import { request } from '../../../utils/request';
import { routes } from '../../../routes';

export const CustomerRouterGuard = () => {
  const location = useLocation();
  const navigate = useNavigate();
  const hasCheckedToken = useRef(false);
  useEffect(() => {
    if (!hasCheckedToken.current) {
      checkToken();
      hasCheckedToken.current = true;
    }
  }, [location]);

  const checkToken = async () => {
    if (!whiteRoutes.includes(location.pathname)) {
      if (!localStorage.getItem('token')) {
        navigate(routes.ADMIN_LOGIN);
        return;
      }
      const res = await request('/admin/token_check', {
        pureData: false
      }).catch(_ => {
        navigate(routes.ADMIN_LOGIN);
      });
      if (res?.code !== '1') {
        navigate(routes.ADMIN_LOGIN);
        return;
      }
    }
  };

  return null;
};